package com.rock.platform.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

public class DateJsonValueProcessor implements JsonValueProcessor {
	public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd HH:mm:ss";
	private DateFormat dateFormat;

	public DateJsonValueProcessor(String datePattern) {
		if ((datePattern == null) || (datePattern.equals("")))
			this.dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		else
			this.dateFormat = new SimpleDateFormat(datePattern);
	}

	public Object processArrayValue(Object value, JsonConfig jsonConfig) {
		Collection<?> array = null;
		JSONArray jsonArray = null;
		try {
			array = (Collection<?>) value;
			jsonArray = new JSONArray();
		} catch (Exception ex) {
			return process(value);
		}

		for (Iterator<?> localIterator = array.iterator(); localIterator
				.hasNext();) {
			Object o = localIterator.next();

			jsonArray.add(process(o));
		}
		return jsonArray;
	}

	public Object processObjectValue(String key, Object value,
			JsonConfig jsonConfig) {
		return process(value);
	}

	private Object process(Object value) {
		if (value instanceof Date) {
			return this.dateFormat.format((Date) value);
		}
		return ((value == null) ? null : value.toString());
	}
}
